//
// Parse.cpp for  in /home/goldbe_y//cpp/Maths/206observ
//
// Made by yoni goldberg
// Login   <goldbe_y@epitech.net>
//
// Started on  Mon May  2 15:13:56 2011 yoni goldberg
// Last update Thu May 26 16:48:48 2011 leo faucon
//

#include <cstdlib>

#include "Parse.hpp"
#include "convert.hpp"


std::string	epur(std::string tmp)
{
  int	i = 0;

  while (tmp[i])
    {
      if (tmp[i] == '\t')
	tmp[i] = ' ';
      i++;
    }
  return (tmp);
}

Parse::Parse(const std::string &str)
{
  int				ind = 0;
  std::string			temp;
  std::ifstream			file(str.c_str());

  getline(file, temp);
  line = string_to_var<int>(temp);
  while (ind < line)
    {
      getline(file, temp);
      tab.push_back(epur(temp));
      ind++;
    }
  file.close();

  int	i = 0;
  while (i < line) (filltabs(tab[i++]));
  //tri();
}

Parse::~Parse()
{
}

std::vector<std::string>		&Parse::get_from_file()
{
  return (tab);
}

void		Parse::filltabs(const std::string &str)
{
  int		ind = 0;
  float		tmp;
  std::string	temp("");

  while (str[ind] == ' ') (ind++);
  while (str[ind] != '\0' && str[ind] != ' ') (temp += str[ind++]);
  tmp = string_to_var<float>(temp);
  val.push_back(tmp);
  temp = "";
  while (str[ind] != '\0' && str[ind] == ' ') (ind++);
  while (str[ind] != '\0' && str[ind] != ' ' && str[ind] != '\n') (temp += str[ind++]);
  tmp = string_to_var<float>(temp);
  coef.push_back(tmp);
}

void					Parse::tri()
{
  int	j = 0;

  while(j < line)
    {
      int	i = 0;
      while (i < line)
	{
	  if (i+1 < (int)val.size())
	    {
	      if (val[i] > val[i+1])
		{
		  float tmp = val[i];
		  val[i] = val[i+1];
		  val[i+1] = tmp;
		  tmp = coef[i];
		  coef[i] = coef[i+1];
		  coef[i+1] = tmp;
		}
	    }
	  i++;
	}
      j++;
    }
}

void	Parse::regroup()
{
  int	j = 0;

  while (j < (int)val.size())
    {
      if (j+1 < (int)val.size())
	{
	  if (val[j] == val[j + 1])
	    {
	      coef[j] += coef[j+1];
	      coef.erase(coef.begin() + j + 1);
	      val.erase(val.begin() + j + 1);
	      line--;
	    }
	}
      j++;
    }
}
